package com.smsquiztest;

import java.io.*;
import java.util.ArrayList;

import android.os.Environment;
import android.telephony.SmsManager;

public class AppModel {

	private static AppModel instance = new AppModel();

    private final String DB_FILE = "botbase.txt";

	private String phoneNumber;
    private ArrayList<String> messages;
    private int index = 0;
	
	public static AppModel getInstance(){
		return instance;
	}

	public void initialize(String phoneNumber) {
		this.phoneNumber = phoneNumber;
        messages = new ArrayList<String>();

        File external = Environment.getExternalStorageDirectory();
        File db = new File(external, DB_FILE);
        if (!db.exists()) {
            File sd = new File(external, "external_sd");
            db = new File(sd, DB_FILE);
        }
        if (db.exists()) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(db.getAbsoluteFile()));
            } catch (FileNotFoundException e) {
                AppLogger.WriteError(e);
            }

            if (reader != null){
                String line;
                try {
                    while((line = reader.readLine()) != null){
                        if(!line.isEmpty()){
                            messages.add(line);
                        }
                    }
                    reader.close();
                } catch (IOException e) {
                    AppLogger.WriteError(e);
                }
            }
        }
	}
	
	public String getPhoneNumber(){
		return phoneNumber;
	}
	
	public void sendNextQuestion(){	
		if(phoneNumber == null || phoneNumber.length() <= 0){
			return;
		}
		String message = "";
		try {
			message = new String(new byte[0], "UTF-8");
		} catch (UnsupportedEncodingException e) {
			AppLogger.WriteError(e);
		}
		message += messages.get(index++);
        if (index >= messages.size()){
            index = 0;
        }
		try{
			SmsManager smsManager = SmsManager.getDefault();
			smsManager.sendTextMessage(phoneNumber, null, message, null, null);		
			AppLogger.Write(message);
		}
		catch (Exception e) {
			AppLogger.WriteError(e);
		}
	}
}
